package com.hxf.web.action;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource; 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
   
import com.hxf.common.AppProps;
import com.hxf.common.DateUtil;
import com.hxf.common.GlobalConstant;
import com.hxf.common.ImageUtils;
import com.hxf.common.PublicUtil;
import com.hxf.dto.AdminUserDto;
import com.hxf.dto.MenuDto;
import com.hxf.dto.RestaurantDto;
import com.hxf.dto.RestaurentUserDto;
import com.hxf.dto.UserDto;
import com.hxf.exception.ServiceException;
import com.hxf.service.facade.ServiceFacade;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven; 

/**
 * 公共Action
 * @author tengyicheng
 * @version [1.0, 2013/09/22]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public abstract class WebActionBase extends ActionSupport implements ModelDriven<Object>{

	private static final long serialVersionUID = 1L;

	protected final org.apache.log4j.Logger logger = Logger.getLogger(getClass());
	@Resource
	protected ServiceFacade serviceFacade;
	
	protected Integer targetPage = 1; 
	protected Integer pageSize=20; 
	protected Integer recordCount; 
	protected Integer pageCount; 
	protected String requestURL;
	protected String webUrl;
	protected String msg;
	
	protected UserDto user;
	
	@Override
	public Object getModel() {
		 
		return null;
	}

	/**
	 * 菜单权限验证（不包括功能权限）
	 * @return
	 */
	protected boolean menuPrivilegeValidate(String url) { 
		boolean urlBool = false;
		Object adminUserDto = getSession().getAttribute("adminUserDto"); //联盟管理员Session
		Object restaurentUserDto = getSession().getAttribute("restaurentUserDtoLogin");//餐厅 Session 
		
		//联盟管理员
		if(null != adminUserDto){
			try {
				
				List<MenuDto> menuList =  serviceFacade.getMenuService().findMenuTree(getAdminUser().getId());
				if ("admin".equals(getAdminUser().getUserName())) {
					urlBool = true;
					return urlBool;
				}
				if (menuList != null && menuList.size() > 0) {
					for (MenuDto menu : menuList) {
						//验证用户是否拥有该地址的权限
						if (PublicUtil.isNotNullAndEmpty(menu.getMenuUrl()) && PublicUtil.isNotNullAndEmpty(url)) {
							if (url.indexOf(menu.getMenuUrl()) > -1) {
								urlBool = true;
								break;
							}
						}
					} 
				}
				if (!urlBool) {
					msg = "你没有访问权限！";
				}
			} catch (ServiceException e) {
				logger.debug(e.getMessage(), e);
			} 
			return urlBool;
		}else if(null != restaurentUserDto){
			try {
				
				List<MenuDto> menuList =  serviceFacade.getMenuService().RestaurentfindMenuTree(getRestaurentUserDto().getId());
				if ("admin".equals(getRestaurentUserDto().getAccount())) {
					urlBool = true;
					return urlBool;
				}
				if (menuList != null && menuList.size() > 0) {
					for (MenuDto menu : menuList) {
						//验证用户是否拥有该地址的权限
						if (PublicUtil.isNotNullAndEmpty(menu.getMenuUrl()) && PublicUtil.isNotNullAndEmpty(url)) {
							if (url.indexOf(menu.getMenuUrl()) > -1) {
								urlBool = true;
								break;
							}
						}
					} 
				}
				if (!urlBool) {
					msg = "你没有访问权限！";
				}
			} catch (ServiceException e) {
				logger.debug(e.getMessage(), e);
			} 
			return urlBool;
		}
		
		return urlBool;
	}
	
	// 得到访问者IP地点
	public String getRemoteIp() {
		HttpServletRequest request = getRequest();
		// update jakdan
		/**
		 * 注视部分为源代码
		 * 
		 * String ip=request.getHeader("x-forwarded-for"); if(ip==null)
		 * ip=request.getRemoteHost(); else if(ip.indexOf(",")>0)
		 * ip=ip.substring(0,ip.indexOf(",")); return ip.trim();
		 */
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null) {

			// ip=request.getRemoteHost(); /** 或者
			// getRemoteAddr()网络上查询得到是获取来访者的IP，而.getRemoteHost()是获取服务器的IP */
			ip = request.getRemoteAddr().trim();
			/**
			 * 可是当我访问系统网站时候，返回的IP地址避免是unknown， 如果 forwarded_for 设成了 off
			 * 　则：X-Forwarded-For： unknown
			 */

			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP").trim();
			}
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP").trim();
			}
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_CLIENT_IP").trim();
			}
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_X_FORWARDED_FOR").trim();
			}
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr().trim();
			}

		} else if (ip.indexOf(",") > 0) {
			logger.error("ip = " + ip);

			ip = ip.substring(0, ip.indexOf(","));
		}
		return ip.trim();
	}
	
	public List<RestaurantDto> getListRestaurantDto() {
		try {
			
			return (List<RestaurantDto>)serviceFacade.getRestaurantService().findByRestaurant(getUser().getUserId());
		} catch (ServiceException e) {
			logger.debug(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 餐厅管理 - 订单信息  
	 * 自能餐厅查看
	 * @return
	 */
	public List<RestaurantDto> getListRestaurantOrAdminDto() {
		try {
			Object adminUserDto = getSession().getAttribute("adminUserDto"); //联盟管理员Session
			Object restaurentUserDto = getSession().getAttribute("restaurentUserDtoLogin");//餐厅 Session
			if(null != adminUserDto){
				//管理员  返回所有
				return (List<RestaurantDto>)serviceFacade.getRestaurantService().findByRestaurant(null);
			}else if(null != restaurentUserDto){
				return (List<RestaurantDto>)serviceFacade.getRestaurantService().findByRestaurant(getRestaurentUserDto().getId());
			}
			
		} catch (ServiceException e) {
			logger.debug(e.getMessage(), e);
		}
		return null;
	}

	public RestaurantDto getRestaurantDto() {
		try {
			//return (RestaurantDto) serviceFacade.getRestaurantService().findByRestaurant();
			return (RestaurantDto) serviceFacade.getRestaurantService().findByRestaurant(getUser().getUserId());
		} catch (ServiceException e) {
			logger.debug(e.getMessage(), e);
		}
		return null;
	}
	public Integer getPageCount(){
		return pageCount;
	}

	public void setPageCount(Integer pageCount) {
		this.pageCount = pageCount;
	}

	public String getRequestURL() {
		return requestURL;
	}

	public void setRequestURL(String requestURL) {
		this.requestURL = requestURL;
	}

	public HttpSession getSession() {
		return ServletActionContext.getRequest().getSession();
	}
	
	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}
	
	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}
	
	public void setAttribute(String key, Object value) {
		getRequest().setAttribute(key, value);
	}
	
	public void println(Object args) throws IOException {
		getResponse().getWriter().println(args);
	}
 
	public ServiceFacade getServiceFacade() {
		return serviceFacade;
	}

	public void setServiceFacade(ServiceFacade serviceFacade) {
		this.serviceFacade = serviceFacade;
	}

	public String getWebUrl() { 
		return getRequest().getScheme()+"://"+getRequest().getServerName()+":"+getRequest().getServerPort() + "/"+ GlobalConstant.PROJECT_NAME;
	}
	
	public String getParameter(String args) {
		return getRequest().getParameter(args);
	}

	public UserDto getUser() { 
		return (UserDto)getSession().getAttribute("userDto");
	} 
	
	public AdminUserDto getAdminUser(){
		return (AdminUserDto)getSession().getAttribute("adminUserDto");
	}
	
	public RestaurentUserDto getRestaurentUserDto(){
		return (RestaurentUserDto)getSession().getAttribute("restaurentUserDtoLogin");
	}
	public String getMsg() {
		return msg;
	}
 
	public void setWebUrl(String webUrl) {
		this.webUrl = webUrl;
	}

	public void setUser(UserDto user) {
		this.user = user;
	}
 
	public void setMsg(String msg) {
		this.msg = msg;
	}
	
	
	public Integer getTargetPage() {
		targetPage = targetPage == null || targetPage <= 0 ? 1 : targetPage;
		return targetPage;
	}

	public void setTargetPage(Integer targetPage) {
		targetPage = targetPage == null || targetPage <= 0 ? 1 : targetPage;
		this.targetPage = targetPage;
	}

	public Integer getPageSize() {
		if (pageSize == null || pageSize <= 0) {
			pageSize = 20;
		}
		return pageSize;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

	public Integer getRecordCount() {
		return recordCount;
	}

	public void setRecordCount(Integer recordCount) {
		this.recordCount = recordCount;

		// pageCount = pageCount == null ? 0 : pageCount;
		int page = this.recordCount % pageSize;
		if (page == 0) {
			pageCount = this.recordCount / pageSize;
		} else {
			pageCount = this.recordCount / pageSize + 1;
		} 
	}
	
	public static void main(String[] args) {
		String[] str = {"星期一","星期二","星期三","星期四","星期五","星期六","星期天"};
		Calendar cal = Calendar.getInstance();
		System.out.println(Calendar.DAY_OF_WEEK);
		System.out.println("String:"+str[Calendar.DAY_OF_WEEK-1]);
		System.out.println("cal:"+cal);
	}
}
